package com.fl.nettydemo.server;

import com.fl.nettydemo.test.test1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.*;

@Service
@ComponentScan("com.fl.nettydemo.test.*")
public class AsynchronousService {
    @Async
    public void springAsynchronousMethod() {
        if (test1.status) {
            test1.status = false;
            Integer method = method(2, 2);
            System.out.println("传输结束:" + method);
        }
    }

    public static Integer method(int threadNum, int timeOut) {
        // 获取线程池

        ExecutorService es = Executors.newFixedThreadPool(2);
        // Future用于执行多线程的执行结果
        Future<Integer> future = es.submit(() -> {
            LocalDateTime before = LocalDateTime.now();
            while (test1.map.size() < 10) {
                long between = ChronoUnit.SECONDS.between(before, LocalDateTime.now());
                if (between > 2) {
                    System.out.println("获取包超时！");
                    break;
                }
                System.out.println("正在计算接包数量...." + test1.map.size() + "---" + between);
            }
            //TimeUnit.SECONDS.sleep(3);
            test1.status = true;
            return null;
        });

        try {
            // futrue.get()测试被执行的程序是否能在timeOut时限内返回字符串
            return future.get(timeOut, TimeUnit.SECONDS);//任务处理超时时间设为 1 秒
        } catch (TimeoutException ex) {
            System.out.println("获取数据超时：" + ex.getMessage());
            try {
                TimeUnit.SECONDS.sleep(timeOut);
                System.out.println("进行请求重发");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

